﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Documents;

namespace DataAchive.Common
{
    public static class DynamicCustomeProperty
    {
        // 添加属性
        public static void AddProperty(dynamic item, string propertyName, object Value)
        {
            var dictionary = item as IDictionary<string, object>;
            if (dictionary != null && dictionary.ContainsKey(propertyName))
            {
                return;
            }
            dictionary.Add(propertyName, Value);
        }

        // 获取动态对象的属性值
        public static object GetPropertyValue(dynamic item, string propertyName)
        {
            var dictionary = item as IDictionary<string, object>;
            if (dictionary != null && dictionary.ContainsKey(propertyName))
            {
                return dictionary[propertyName];
            }
            return null;
        }

        // 属性赋值
        public static void SetPropertyValue(dynamic item, string propertyName, object Value)
        {
            var dictionary = item as IDictionary<string, object>;
            if (dictionary != null && dictionary.ContainsKey(propertyName))
            {
                item[propertyName] = (object)Value;
            }
            return;
        }

        // 移除属性
        public static void RemoveProperty(dynamic item, string propertyName)
        {
            var dictionary = item as IDictionary<string, object>;
            if (dictionary != null && dictionary.ContainsKey(propertyName))
            {
                return;
            }
            dictionary.Remove(propertyName);
        }

        // 获取动态对象的属性名列表
        public static List<string> GetDynamicObjectProperties(List<dynamic> data, ObservableCollection<string>  classIfyPriority)
        {
            var properties = new List<string>();
            if (data.Count > 0)
            {
                var firstItem = data[0];
                var dictionary = firstItem as IDictionary<string, object>;
                if (dictionary != null)
                {
                    properties.AddRange(dictionary.Keys);
                }
            }
            properties = properties.OrderBy(w => Array.IndexOf(classIfyPriority.ToArray(), w)).ToList();
            return properties;
        }


    }
}
